package logs

import (
	"bytes"
	"fmt"
	"github.com/sirupsen/logrus"
	"io"
	"os"
	"time"
)

type CustomFormat struct {
	AppName string
}

const (
	cBlack = iota + 30
	cRed
	cGREEN
	cYELLOW
	cBLUE
	cPURPLE
	cCyan
	cGray
)

func (c *CustomFormat) Format(entry *logrus.Entry) ([]byte, error) {
	var color int
	switch entry.Level {
	case logrus.DebugLevel:
		color = cCyan
	case logrus.InfoLevel:
		color = cBLUE
	case logrus.WarnLevel:
		color = cYELLOW
	case logrus.ErrorLevel:
		color = cRed
	default:
		color = cGray
	}

	timeFormat := entry.Time.Format(time.DateTime)

	var b *bytes.Buffer
	if entry.Buffer == nil {
		b = &bytes.Buffer{}
	} else {
		b = entry.Buffer
	}

	// 文件路径:行号
	fileInfo := fmt.Sprintf("\033[%dm [%s:%d] \033[0m", cBLUE, entry.Caller.File, entry.Caller.Line)
	// 设置格式
	fmt.Fprintf(b, "\033[32m[%s]\033[0m \033[%dm[%s]\033[0m \033[30m[%s]\033[0m %s %s \n",
		c.AppName, color, entry.Level, timeFormat, fileInfo, entry.Message)
	return b.Bytes(), nil
}

func InitLogrus(appName string) {
	var log = logrus.New()
	// 标准输出,文件输出
	var writers []io.Writer
	consoleOut := os.Stdout
	writers = append(writers, consoleOut)
	Environment := "production"

	if Environment == "production" {
		// todo: file rotate
		fileOut, _ := os.OpenFile("./gin.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
		writers = append(writers, fileOut)
	}

	log.SetOutput(io.MultiWriter(writers...))
	log.SetLevel(logrus.InfoLevel)
	// 将调用的函数名添加为字段, 开启这个模式会增加性能开销
	log.SetReportCaller(true)
	// gin.DefaultWriter = log.Out
	logrus.SetLevel(logrus.InfoLevel)
	logrus.SetReportCaller(true)
	logrus.SetFormatter(&CustomFormat{
		AppName: appName,
	})
}
